package org.smi;

import java.io.*;
import java.net.URL;
import java.util.concurrent.CountDownLatch;

/**
 * @Author: ism
 * @Platform: Mac
 * @Date: 下午7:54 2018/6/30
 */
public class RunExec extends Thread {

    private String url;
    private String saveDir;
    private String fileName;
    private int id;
    private CountDownLatch countDownLatch;

    public void setUrl(String url) {
        this.url = url;
    }

    public void setSaveDir(String saveDir) {
        this.saveDir = saveDir;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        download(url, saveDir, fileName, id, countDownLatch);
    }

    public static void download(String url, String saveDir, String fileName, int id, CountDownLatch countDownLatch) {
        BufferedOutputStream bos = null;
        InputStream is = null;
        try {
            byte[] buff = new byte[8192];
            is = new URL(url).openStream();
            File file = new File(saveDir, fileName);
            file.getParentFile().mkdirs();
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int count = 0;
            while ((count = is.read(buff)) != -1) {
                bos.write(buff, 0, count);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            countDownLatch.countDown();
            System.out.println("下载完成 -> " + id);
        }
    }
}
